﻿using Microsoft.Extensions.DependencyInjection;
using System.Reflection;

public static class ServiceCollectionExtensions
{
    public static IServiceCollection AddServicesByConvention(this IServiceCollection services)
    {
        // 获取当前程序集
        var assembly = Assembly.GetExecutingAssembly();

        // 查找所有实现了以"I"开头的接口的非抽象类
        var serviceTypes = assembly.GetTypes()
            .Where(t => !t.IsAbstract && !t.IsInterface &&
                       t.GetInterfaces().Any(i => i.Name.StartsWith("I") &&
                                               i.Name.Substring(1) == t.Name));

        foreach (var type in serviceTypes)
        {
            var interfaceType = type.GetInterface($"I{type.Name}");
            if (interfaceType != null)
            {
                // 这里使用Scoped生命周期，你可以根据需要修改
                services.AddScoped(interfaceType, type);
            }
        }

        return services;
    }
}